//
//  EpointWebInfoViewControllerCache.m
//  EpointFrame5
//
//  Created by 李亚春 on 14-3-12.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EpointWebInfoViewControllerCache.h"
#import "EpointWebInfoModel.h"
#import "EpointWebInfoListCell.h"
#import "MJRefresh.h"
#import "EpointWebInfoDetailViewController.h"
#import "EpointWebInfoListCellUniversalCell.h"
#import "EpointWebInfoDetailViewController_V2.h"
#import "EAD_WebInfo_List_CellTableViewCell.h"

#define WebInfoListCacheKey @"C"

@interface EpointWebInfoViewControllerCache ()
{
    NSMutableArray *dataArray;
    UITableView *tv;
    UISearchBar *sb;
    UISearchDisplayController *searchController;
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
    //列表索引
    int pageIndex;
    
    //每页列表数量
    int listPageCount;
    
    //搜索关键字
    NSString *keyWork;
    
    NSString *CategoryGuid;
}
@end

@implementation EpointWebInfoViewControllerCache

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    CategoryGuid = [self.passParam objectForKey:@"categoryguid"];
    
    pageIndex = 1;
    listPageCount = 20;
    keyWork = @"";
    
    dataArray = [[NSMutableArray alloc]init];
    sb = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, AppWidth, 44)];
    sb.placeholder = @"关键字检索";
    sb.delegate = self;
    [self.view addSubview:sb];
    
    
    searchController = [[UISearchDisplayController alloc]initWithSearchBar:sb contentsController:self];
    searchController.searchResultsTableView.backgroundColor = [UIColor clearColor];
    searchController.searchResultsTableView.separatorColor = [UIColor clearColor];
    searchController.delegate = self;
    searchController.searchResultsDataSource = self;
    searchController.searchResultsDelegate = self;
    searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    searchController.searchResultsTableView.bounces = NO;
    
    tv = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, AppWidth, AppHeight-SystemTakeHeight-44)];
    tv.rowHeight = 75;
    tv.dataSource = self;
    tv.delegate = self;
    [self.view addSubview:tv];
    
    [self getData:pageIndex taskid:1 showProgress:YES];
    [self addHeader];
    [self addFooter];
}

-(void)getData:(int)_index taskid:(int)taskid showProgress:(BOOL)showProgress
{
    if (showProgress) {
        [self showMBPHUD];
    }
   
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:[NSString stringWithFormat:@"%i",listPageCount] forKey:@"pagesize"];
    [params setObject:keyWork forKey:@"keyword"];
    [params setObject:CategoryGuid forKey:@"categoryguid"];
    [params setObject:[NSString stringWithFormat:@"%i",_index] forKey:@"CurrentPageIndex"];
    [self startTask:@"WebInfo_GetView_Tsk_c" withParams:params withTaskId:taskid];
}

-(void)addHeader
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = tv;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        pageIndex = 1;
        [self getData:pageIndex taskid:2 showProgress:NO];
    };
    _header = header;
}

- (void)addFooter
{
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = tv;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        pageIndex++;
        [self getData:pageIndex taskid:1 showProgress:NO];
    };
    _footer = footer;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *WebinfolistItem = @"EpointWebInfoListCellUniversalCell";
    EpointWebInfoListCellUniversalCell *cell = (EpointWebInfoListCellUniversalCell *)[tableView dequeueReusableCellWithIdentifier:WebinfolistItem];
    
    if (cell == nil) {
        
        cell = [[EpointWebInfoListCellUniversalCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                                         reuseIdentifier:WebinfolistItem
                                                     containingTableView:tableView // Used for row height and selection
                                                      leftUtilityButtons:nil
                                                     rightUtilityButtons:[self rightButtons]];
        cell.delegate = self;
    }
    
    EpointWebInfoModel *m = [dataArray objectAtIndex:indexPath.row];
    cell.lbTitle.text = m.txtTitle;
    
    cell.lbPerson.text = [[[m.PostDate componentsSeparatedByString:@" "]objectAtIndex:0]stringByReplacingOccurrencesOfString:@"/" withString:@"."];
    cell.lbFeedBack.text = [NSString stringWithFormat:@"%@ 回复",m.FeedBackCount];
    
    if ([m.IsRead isEqualToString:@"1"]) {
        cell.ivStatus.hidden = YES;
        [cell.lbTitle setFrame:CGRectMake(7, 3, AppWidth-14, 45)];
        
    }
    else
    {
        cell.ivStatus.hidden = NO;
        [cell.lbTitle setFrame:CGRectMake(cell.ivStatus.frame.origin.x+cell.ivStatus.frame.size.width+5,3, AppWidth-20, 45)];
    }
    
    if ([m.HasAttach isEqualToString:@"1"]) {
        cell.lbAttach.hidden = NO;
        cell.lbFeedBack.frame = CGRectMake(AppWidth/2-7, 49, AppWidth-cell.lbPerson.frame.size.width-cell.lbAttach.frame.size.width-10, 20);
    }
    else
    {
        cell.lbAttach.hidden = YES;
        cell.lbFeedBack.frame = CGRectMake(AppWidth/2-7, 49, AppWidth-cell.lbPerson.frame.size.width-10, 20);
    }
    
    if ([m.FeedBackCount integerValue]==0) {
        cell.lbFeedBack.hidden = YES;
    }
    else
    {
        cell.lbFeedBack.hidden = NO;
    }
    
    return cell;
    
}
 

- (NSArray *)rightButtons
{
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f]
                                                title:@"收藏"];
    return rightUtilityButtons;
}
 */

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *WebinfolistItem = @"EAD_WebInfo_List_CellTableViewCell";
    EAD_WebInfo_List_CellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:WebinfolistItem];
    if (cell==nil) {
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"EAD_WebInfo_List_CellTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    EpointWebInfoModel *m = [dataArray objectAtIndex:indexPath.row];
    cell.lbTitle.text = m.txtTitle;
    cell.lbSender.text = m.PostUserName;
    if ([m.FeedBackCount integerValue]>0) {
        cell.lbSender.text = [NSString stringWithFormat:@"%@条回复",m.FeedBackCount];
    }
    cell.lbTime.text = [[m.PostDate componentsSeparatedByString:@" "]objectAtIndex:0];
    if ([m.HasAttach isEqualToString:@"1"]) {
        cell.ivAttach.hidden = NO;
    }
    else
    {
        cell.ivAttach.hidden = YES;
    }
    
    if ([m.IsRead isEqualToString:@"1"]) {
        cell.ivStatus.hidden = YES;
        [cell.lbTitle setTextColor:[UIColor blackColor]];
    }
    else
    {
        cell.ivStatus.hidden = NO;
        [cell.lbTitle setTextColor:[UIColor redColor]];
    }
    
    if ([m.IsRead isEqualToString:@"1"]&&![m.HasAttach isEqualToString:@"1"]) {

    }
    
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 67;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    EpointWebInfoModel *m = [dataArray objectAtIndex:indexPath.row];
    m.IsRead = @"1";
    [dataArray setObject:m atIndexedSubscript:indexPath.row];
    [tv reloadData];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:[self.passParam objectForKey:@"categoryguid"] forKey:@"CategoryGuid"];
    [params setObject:m.InfoGuid forKey:@"InfoGuid"];
    [params setObject:m.Content forKey:@"Content"];
    [params setObject:@"信息详情" forKey:@"title"];
    EpointWebInfoDetailViewController_V2 *wi = [[EpointWebInfoDetailViewController_V2 alloc]init];
    wi.passParam = params;
    [self.navigationController pushViewController:wi animated:YES];
}

- (BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell {
    return YES;
}

-(void)searchDisplayController:(UISearchDisplayController *)controller willHideSearchResultsTableView:(UITableView *)tableView
{
    [tv setHidden:NO];
}

-(void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView
{
    [tv setHidden:YES];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [dataArray removeAllObjects];
    pageIndex = 1;
    keyWork = searchText;
    [self getData:pageIndex taskid:1 showProgress:YES];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"searchBarSearchButtonClicked");
    [searchBar resignFirstResponder];
    
    [searchController setActive:NO animated:YES];
}


-(void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj
{
    [self hideMBPHUD];
    //处理异常信息
    NSMutableArray *arr = (NSMutableArray*)obj;
    if (![[arr objectAtIndex:0]isEqualToString:@"1"]) {
        [self toastMessage:[arr objectAtIndex:1]];
        [_footer endRefreshing];
        [_header endRefreshing];
        return;
    }
    
    if (taskId==1) {
        
        NSMutableArray *listData = [arr objectAtIndex:2];
        
        for (EpointWebInfoModel *m in listData) {
            
            for (int j=0; j<dataArray.count; j++) {
                
            }
            
            [dataArray addObject:m];
        }
        [tv reloadData];
        [searchController.searchResultsTableView reloadData];
        [_footer endRefreshing];
        if (listData.count<listPageCount&&keyWork.length==0) {
            [_footer removeFromSuperview];
        }
    }
    else if (taskId==2)
    {
        [dataArray removeAllObjects];
        NSMutableArray *listData = [arr objectAtIndex:2];
        
        for (EpointWebInfoModel *m in listData) {
            
            for (int j=0; j<dataArray.count; j++) {
                
            }
            
            [dataArray addObject:m];
        }
        [tv reloadData];
        [_header endRefreshing];
    }
}

@end
